<template>
  <el-tabs v-model="active" :type="styleType" :tab-position="tabPosition" :closable="closable" @tab-click="handleTabClick">
    <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name" :lazy="tab.lazy">
      <form-render ref="tabs_form" :options="tab" v-model:data="localData" :pageId="$attrs.pageId" :inGrid="true" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import FormRender from '../../views/form-render/index.vue';

export default {
  name: 'AnvilTabs',
  components: { FormRender },
  inheritAttrs: false,
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    tabs: {
      type: Array,
      default: () => []
    },
    formData: {
      type: Object,
      default: () => {}
    },
    styleType: {
      type: String,
      default: ''
    },
    tabPosition: {
      type: String,
      default: 'top'
    },
    closable: {
      type: Boolean,
      default: false
    },
    tabClick: {
      type: Function,
      default: undefined
    }
  },
  data() {
    return {
      active: '',
      localData: {}
    };
  },
  watch: {
    modelValue: {
      handler(v) {
        this.active = v;
      },
      immediate: true
    },
    active: {
      handler(v) {
        this.$emit('update:modelValue', v);
      }
    },
    formData: {
      handler(v) {
        this.localData = v;
      },
      immediate: true,
      deep: true
    },
    localData: {
      handler(v) {
        this.$emit('update:formData', v);
      },
      deep: true
    }
  },
  methods: {
    handleTabClick(tab, event) {
      if (this.tabClick && typeof this.tabClick === 'function') {
        this.tabClick(tab, event);
      }
    },
    validate() {
      if (this.$refs.tabs_form && this.$refs.tabs_form.length) {
        const promises = [];
        const len = this.$refs.tabs_form.length;
        for (let i = len - 1; i >= 0; i--) {
          promises.push(this.$refs.tabs_form[i].validateAvueForm());
        }
        return promises;
      } else {
        return [];
      }
    }
  }
};
</script>
